'use strict'

const Controller = require('egg').Controller

class BlogsController extends Controller {
  async index() {
    const { ctx } = this
    ctx.body = 'hi, egg'
  }

  // 博客基于标题搜索接口-模糊搜索接口
  async blogsSearch() {
    const { ctx, app } = this
    try {
      const { keywords } = ctx.query
      const sql = `select * from blogs where title like '%${keywords}%'`
      const data = await app.mysql.query(sql)
      ctx.body = new ctx.SuccessModel(data)
    } catch (err) {
      ctx.body = new ctx.FailModel(err)
    }
  }

  async findBlogsList() {
    const { ctx, app } = this
    const { page = 1, size = 5 } = ctx.query
    try {
      const sql = `select * from blogs inner join users where users.id = blogs.userId limit ? offset ?`
      const data = await app.mysql.query(sql, [size * 1, (page - 1) * size])
      ctx.body = new ctx.SuccessModel('success', data)
    } catch (err) {
      ctx.body = new ctx.FailModel('fail', err)
    }
  }
  async addBlogsItem() {
    const { ctx, app } = this
    try {
      const { title, content } = ctx.request.body
      const { id } = ctx.state.userInfo
      // blogs表中userId 对应 users表中的id
      const data = await app.mysql.insert('blogs', {
        title,
        content,
        userId: id,
      })
      if (data.affectedRows) {
        ctx.body = new ctx.SuccessModel('success', data)
      } else {
        ctx.body = new ctx.FailModel('fail')
      }
    } catch (err) {
      ctx.body = new ctx.FailModel('fail', err)
    }
  }
  async updateBlogsItem() {
    const { ctx, app } = this
    try {
      const { title, content, blogId } = ctx.request.body
      const data = await app.mysql.update(
        'blogs',
        { title, content }, // 修改的内容
        {
          // 更新的条件
          where: {
            blogId,
          },
        }
      )
      if (data.affectedRows) {
        ctx.body = new ctx.SuccessModel('success', data)
      } else {
        ctx.body = new ctx.FailModel('修改失败')
      }
    } catch (err) {
      ctx.body = new ctx.FailModel('fail', err)
    }
  }
  async deleteBlogsItem() {
    const { ctx, app } = this
    const { ids } = ctx.request.body
    let sql = `delete from blogs where 1+1 `
    let deleteData
    if (Array.isArray(ids)) {
      // 删除多个
      sql += `and codeId in (${ids.join(',')})`
      deleteData = await app.mysql.query(sql)
    } else {
      sql += `and codeId=?`
      deleteData = await app.mysql.query(sql, [ids])
    }
    ctx.body = new ctx.SuccessModel({ deleteData, sql })
  }
}

module.exports = BlogsController
